import React from 'react'
import { Popover } from 'antd'
import { isEmpty } from 'lodash'
import request from 'helpers/service'
import { Download } from 'kyz-icon'
import { MatchApiUrl, GetLocalStorage } from 'util'
import './style.less'
import { config } from 'process'

const exportType = {
  excel: '导出数据',
  chart: '导出图片'
}

export default class ExportExcel extends React.PureComponent {
  static defaultProps = {
    multiple: false,
    showMore: false,
    dataType: 'excel'
  }

  constructor() {
    super()
    this.state = {
      HIDEDWNLOAD: false
    }
  }

  componentDidMount() {
    this.setState({
      HIDEDWNLOAD: GetLocalStorage('HIDEDWNLOAD') === 'true'
    })
  }

  setConfig = (data) => {
    const { dataType, exportChart, eventId = '', event, eventParams } = data
    if (dataType === 'excel') {
      const {
        link,
        linkParam = {},
        fileName = '',
        fileType = 'xls',
        params = {},
        downloadExcel,
        method
      } = data
      return {
        dataType,
        link,
        linkParam,
        fileName,
        fileType,
        params,
        downloadExcel,
        method,
        eventId,
        event,
        eventParams
      }
    }
    if (dataType === 'pdf') {
      const { link, fileName = '', fileType } = data
      return {
        dataType,
        link,
        fileName,
        fileType,
        eventId,
        event,
        eventParams
      }
    }
    return {
      dataType,
      exportChart,
      eventId,
      event,
      eventParams
    }
  }

  RequestExcel = (url, params, name, method) => {
    request({
      responseType: 'arraybuffer',
      headers: {
        'Content-Type': 'application/vnd.ms-excel'
      },
      method,
      url,
      params
    }).then((res) => {
      const disposition = res.headers['content-disposition']
      const fileName = disposition.slice(disposition.indexOf('""') + 1, -1)
      const blob = new Blob([res.data])
      const link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = decodeURI(escape(fileName))
      link.click()
      link.remove()
    })
  }

  // 导出excel
  exportExcel = (config) => {
    const { downloadExcel } = config
    let { link } = config
    const { linkParam, fileType, fileName, params, method = 'GET' } = config
    if (downloadExcel) {
      downloadExcel()
      return
    }
    let defaultName = '数据表格.xls'
    if (fileName && fileType) {
      defaultName = `${fileName}.${fileType}`
    }
    if (method === 'POST') {
      this.RequestExcel(link, params, defaultName, method, config)
      return
    }
    if (!isEmpty) {
      link = MatchApiUrl(link, linkParam)
    }
    this.RequestExcel(link, params, defaultName, method, config)
  }

  // 导出图片
  exportChart = () => {
    config.exportChart()
  }

  export = (config) => {
    const { dataType } = config
    if (dataType === 'excel') {
      this.exportExcel(config)
    }
    if (dataType === 'chart') {
      this.exportChart(config)
    }
  }

  renderMultipleList = () => {
    const { config } = this.props
    const list = config.map((item, index) => {
      const { text, dataType } = item
      const configPram = this.setConfig(item)
      return (
        <li
          key={`export-${index}`}
          className="multipleExportBtnInfo"
          onClick={() => this.export(configPram)}>
          {text || exportType[dataType]}
        </li>
      )
    })
    return list
  }

  render() {
    const { multiple, showMore, exportIcon, placement = {} } = this.props
    const { HIDEDWNLOAD } = this.state
    if (!multiple && !showMore) {
      const config = this.setConfig(this.props)
      return (
        <div className={`commonExport ${HIDEDWNLOAD ? 'disabled' : ''}`}>
          {exportIcon ? (
            <span>
              <Download onClick={() => this.export(config)} style={{ fontSize: '18px' }} />
            </span>
          ) : (
            <span>
              <Download onClick={() => this.export(config)} style={{ fontSize: '18px' }} />
            </span>
          )}
        </div>
      )
    }
    if (multiple) {
      const config = this.setConfig(this.props)
      return (
        <Popover placement="bottom" content={this.renderMultipleList()}>
          {exportIcon ? (
            <span>
              <Download style={{ fontSize: '18px' }} />
            </span>
          ) : (
            <span>
              <Download style={{ fontSize: '18px' }} />
            </span>
          )}
        </Popover>
      )
    }
    if (showMore) {
      return (
        <Popover placement="bottom" {...placement} content={this.renderMultipleList()}>
          <div className={`moreExport ${HIDEDWNLOAD ? 'disabled' : ''}`}>
            {exportIcon ? (
              <span>
                <Download style={{ fontSize: '18px' }} />
              </span>
            ) : (
              <span>
                <Download style={{ fontSize: '18px' }} />
              </span>
            )}
          </div>
        </Popover>
      )
    }

    if (multiple && !showMore) {
      return 'multiple和showMore不可同为true'
    }
    return null
  }
}
